<template>
  <div class="header">
    <backButton/>
  </div>
  <component :is="pluginComponent" v-if="pluginComponent" />
  <div v-else>
    <p>插件加载中...</p>
  </div>
</template>

<script setup lang="ts">
import { shallowRef, onMounted, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import backButton from '../../src/components/backButton.vue';
import { ElMessageBox, ElMessage } from 'element-plus';

declare const electronAPI: any;
declare const pluginAPI: any;
declare const nodeAPI: any;
const route = useRoute();
const router = useRouter();
const pluginComponent = shallowRef<any>(null); // 使用 shallowRef 替代 ref

// Node.js依赖检查函数
const checkPluginDependencies = async (pluginName: string) => {
  try {
    console.log(`检查插件 ${pluginName} 的依赖...`);
    
    // 构建插件路径
    const pluginPath = `src/plugins/${pluginName}`;
    const dependencyResult = await nodeAPI.checkPluginDependencies(pluginPath);
    
    if (!dependencyResult.success) {
      // 如果检查失败但不是因为缺少依赖，则显示警告但继续加载
      if (dependencyResult.error && !dependencyResult.error.includes('无package.json文件')) {
        console.warn('依赖检查警告:', dependencyResult.error);
        ElMessage.warning('依赖检查遇到问题，插件可能无法正常运行');
      }
      return;
    }
    
    // 如果有缺失的依赖包，询问用户是否安装
    if (dependencyResult.installedPackages && dependencyResult.installedPackages.length > 0) {
      const missingDeps = dependencyResult.installedPackages.join(', ');
      const message = `插件 ${pluginName} 需要安装以下依赖：${missingDeps}\n是否立即安装？`;
      
      const result = await ElMessageBox.confirm(message, '依赖检查', {
        confirmButtonText: '安装依赖',
        cancelButtonText: '跳过',
        type: 'warning'
      }).catch(() => 'cancel');
      
      if (result === 'confirm') {
        ElMessage.info('正在安装依赖，请稍候...');
        
        // 监听安装进度
        const progressHandler = (data: { message: string; progress: number }) => {
          console.log('依赖安装进度:', data);
          if (data.progress >= 100) {
            ElMessage.success('依赖安装完成');
            nodeAPI.removeNodeListeners();
          }
        };
        
        nodeAPI.onPluginDependencyProgress(progressHandler);
        
        try {
          const installResult = await nodeAPI.checkPluginDependencies(pluginPath);
          if (installResult.success) {
            ElMessage.success('依赖安装成功');
          } else {
            ElMessage.error(`依赖安装失败: ${installResult.error}`);
          }
        } catch (error) {
          console.error('依赖安装失败:', error);
          ElMessage.error('依赖安装失败，插件可能无法正常运行');
        } finally {
          nodeAPI.removeNodeListeners();
        }
      }
    } else {
      console.log(`插件 ${pluginName} 依赖检查通过`);
    }
  } catch (error) {
    console.error('依赖检查失败:', error);
    ElMessage.warning('依赖检查失败，插件可能无法正常运行');
  }
};

onMounted(async () => {
  const pluginName = route.params.pluginName;
  try {
    // 首先检查Node.js依赖
    await checkPluginDependencies(pluginName as string);
    
    // 版本检查
    const hasUpdate = await pluginAPI.checkPluginUpdate(pluginName);
    if (hasUpdate) {
      ElMessageBox.confirm(`${pluginName}发现新版本，是否立即更新？`, '更新提示', {
        confirmButtonText: '更新',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除旧插件
        await pluginAPI.deletePlugin(pluginName); 
        // 重新下载
        await electronAPI.downloadPlugin(pluginName, 
          `http://10.169.128.20/files/plugins/${pluginName}.zip`);
        ElMessage.success('更新成功，请重新打开插件');
        router.push('/');
      });
      return;
    }
    const manifestPath = await electronAPI.getMainfestPath(pluginName)
    const response = await fetch(manifestPath)
    const manifest = await response.json()

    if (manifest.type.endsWith('vue')) {
      pluginComponent.value = (await import(
        `../plugins/${pluginName}/${pluginName}.vue`
      )).default;
    } else if (manifest.entry.endsWith('html')) {
      const path = await electronAPI.getPluginHtmlPath(pluginName)
      await electronAPI.createPluginWindow({
        pluginName,
        htmlPath: path
      });
      console.log('html路径', path)
      // 轮询检查窗口是否存在
      const checkWindowClosed = async () => {
        try {
          const isOpen = await electronAPI.isWindowOpen(pluginName);
          if (!isOpen) {
            router.push('/');
          } else {
            setTimeout(checkWindowClosed, 1000);
          }
        } catch (error) {
          console.error('检查窗口状态失败:', error);
          router.push('/');
        }
      };
      checkWindowClosed();
    }
  } catch (error) {
    console.error(`加载插件 ${pluginName} 失败:`, error);
    router.push('/');
  }
});
</script>